package com.ayu.shortlink.project.mq.consumer;

import com.ayu.shortlink.project.common.constant.RedisKeyConstant;
import com.ayu.shortlink.project.dto.biz.ShortLinkStatsRecordDTO;
import com.ayu.shortlink.project.service.ShortLinkService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.locks.LockSupport;

/**
 * 延迟记录短链接统计组件
 */
@Component
@Deprecated
@RequiredArgsConstructor
public class DelayShortLinkStatsConsumer implements InitializingBean {
    private final RedissonClient redissonClient;
    private final ShortLinkService shortLinkService;

    public void onMessage(){
        Executors.newSingleThreadExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable runnable) {
                Thread thread = new Thread(runnable);
                thread.setName("DelayShortLinkStatsConsumer");
                thread.setDaemon(Boolean.TRUE);
                return thread;
            }
        }).execute(() -> {
            //获取延迟队列
            RBlockingDeque<ShortLinkStatsRecordDTO> blockingDeque = redissonClient.getBlockingDeque(RedisKeyConstant.DELAY_QUEUE_STATS_KEY);
            RDelayedQueue<ShortLinkStatsRecordDTO> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            for (;;){
                try {
                    ShortLinkStatsRecordDTO statsRecordDTO = delayedQueue.poll();
                    if(statsRecordDTO != null){
                        shortLinkService.shortLinkStats(statsRecordDTO);
                        continue;
                    }
                    LockSupport.parkUntil(500);
                }catch (Throwable ignored) {
                }
            }
        });
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        onMessage();
    }
}
